<?php

namespace App\Services\BuyGoldCash;

use App\Models\User;
use Illuminate\Support\Facades\DB;

class BuyGoldCash
{
    protected User $user;

    protected int $beans = 0;

    protected $payCode = null;

    public function __construct(User $user, $beans, $payCode = null)
    {
        $this->user = $user;
        $this->beans = $beans;
        $this->payCode = $payCode;
    }

    protected function execute()
    {
        $price = big_decimal(cs('storm')->a_gold_bean_buy_cashes);

        if ($price->isLessThanOrEqualTo(0)) return;

        $cashes = $price->multipliedBy($this->beans);

        DB::transaction(function () use ($cashes) {
            account_beans($this->user)->minusFromBuyingCashes($this->beans);
            account_cashes($this->user)->plusCashesFromBeans($cashes);
        });
    }

    public function buy()
    {
        if (empty($this->payCode)) return;

        $this->execute();
    }
}
